package com.gameapplet.challenge.controller;

import com.alibaba.fastjson.JSONObject;
import com.gameapplet.WxPay.controller.WxPayController;
import com.gameapplet.cash.model.Balance;
import com.gameapplet.cash.model.MoneyAlloc;
import com.gameapplet.cash.model.Red;
import com.gameapplet.cash.model.RedStatus;
import com.gameapplet.cash.service.Impl.BalanceServiceImpl;
import com.gameapplet.cash.service.Impl.MoneyAllocServiceImpl;
import com.gameapplet.cash.service.Impl.RedServiceImpl;
import com.gameapplet.cash.service.Impl.RedStatusServiceImpl;
import com.gameapplet.challenge.model.Challenge;
import com.gameapplet.challenge.model.ChallengeTest;
import com.gameapplet.challenge.service.Impl.ChallengeTestServiceImpl;
import com.gameapplet.challenge.service.Impl.ChallengeServiceImpl;
import com.gameapplet.question.model.Question;
import com.gameapplet.question.service.Impl.QuestionServiceImpl;
import com.gameapplet.util.*;
import com.gameapplet.challenge.model.ChallengeStatus;
import com.gameapplet.challenge.service.Impl.ChallengeStatusServiceImpl;
import com.gameapplet.util.GetUUID;
import com.gameapplet.util.MathRandom;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/challenge")
public class ChallengeController {

    @Resource(name = "challengeService")
    ChallengeServiceImpl challengeService;

    @Resource(name = "balanceService")
    BalanceServiceImpl balanceService;

    @Resource(name = "questionService")
    QuestionServiceImpl questionService;

    @Resource(name = "challengeTestService")
    ChallengeTestServiceImpl challengeTestService;

    @Resource(name = "challengeStatusService")
    ChallengeStatusServiceImpl challengeStatusService;

    @Resource(name = "redStatusService")
    RedStatusServiceImpl redStatusService;

    @Resource(name = "redService")
    RedServiceImpl redService;

    @Resource(name = "moneyAllocService")
    MoneyAllocServiceImpl moneyAllocService;

    private List<ChallengeTest> challengeTestList;

    @RequestMapping(value = "/creatChallenge/{isbalance}",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String creatChallenge(@RequestBody Map<String,Object> models, @PathVariable(value = "isbalance") String isbalance, HttpServletRequest request) throws Exception {
//        String s = DecryptUtils.decrypted(challenge.getEncryDate());
//        Integer paymoney = Integer.parseInt(s);
        Challenge challenge = JsonXmlUtils.map2obj((Map<String, Object>) models.get("challenge"),Challenge.class);
        System.out.println(models.get("challenge"));
        System.out.println(models.get("moneyAlloc"));
        String rank = models.get("moneyAlloc").toString().replaceAll("=",":");
        System.out.println(rank);
        List<MoneyAlloc> moneyAllocList = JSONObject.parseArray(rank,MoneyAlloc.class);
        Integer paymoney = "".equals(challenge.getEncryDate())?0:Integer.parseInt(challenge.getEncryDate());
        Map map = new HashMap();
        boolean isOk=false;
        if("1".equals(isbalance)){
            if (paymoney>=0){
                //调用微信支付paymoney为剩余需要支付金额
                System.out.println(paymoney);
//                WxPayController wxPayController = new WxPayController();
//                map = wxPayController.wxPay("1",challenge.getOpenid(),paymoney.toString(),request);
//                if (map!=null) {
                    isOk = true;
//                }
            }
            else {
                //直接使用余额付款
                Balance balance = new Balance();
                balance.setOpenid(challenge.getOpenid());
                balance.setBalance(paymoney.doubleValue());
                balanceService.updateBalanceById(balance);
                isOk = true;
            }
        }
        else {
            //直接支付
            System.out.println(paymoney);
            WxPayController wxPayController = new WxPayController();
            map = wxPayController.wxPay("1",challenge.getOpenid(),paymoney.toString(),request);
            if(map!=null){
                isOk = true;
            }
        }
        if (isOk) {
            challenge.setChallengeid(GetUUID.getUUID());
            challengeService.insertChallenge(challenge);
            if("2".equals(challenge.getChallengeTypeid())) {
                for(int i = 0;i<moneyAllocList.size();i++){
//                    System.out.println(moneyAllocList.get(i));
                    moneyAllocList.get(i).setAllocMoneyid(GetUUID.getUUID());
                    moneyAllocList.get(i).setChallengeid(challenge.getChallengeid());
                    moneyAllocService.insertMoneyAlloc(moneyAllocList.get(i));
                }
            }
//            creatTest(challenge.getChallengeTime(),challenge.getChallengeid());
            map.put("msg","paysuccess");
            String jsonStr = JSONObject.toJSONString(map);
            return jsonStr;
        }
        map.put("msg","payfail");
        String jsonStr = JSONObject.toJSONString(map);
        return jsonStr;

    }

    public void creatTest(Integer challengeTime,String challengeid) {
        int[] a = MathRandom.MyRandom(challengeTime, questionService.selectQuestionNum());
        List<Question> questionList = questionService.selectQuestionlist();
        challengeTestList = new ArrayList<>();
        for (Integer x : a) {
            ChallengeTest challengeTest = new ChallengeTest();
            challengeTest.setChallengeTestid(GetUUID.getUUID());
            challengeTest.setChallengeid(challengeid);
            challengeTest.setQuestionid(questionList.get(x).getQuestionid());
            challengeTestList.add(challengeTest);
        }
        for (ChallengeTest c : challengeTestList) {
            System.out.println("Challengeid==" + c.getChallengeid() +
                    "--Questionid==" + c.getQuestionid() + "--ChallengeTestid==" + c.getChallengeTestid());
        }
        challengeTestService.insertChallengeTest(challengeTestList);
    }


    @RequestMapping("/creatChallenge/{isbalance}")
    @ResponseBody
//    ,@RequestBody Red  red
    public String creatChallenge(@RequestBody Challenge challenge, HttpServletRequest request, @PathVariable(value = "isbalance") String isbalance) {

//      System.out.println(isbalance);, @RequestParam("isbalance") String isbalance
        if (isbalance == "1") {
            Balance balance = balanceService.selectBalanceByOpenid(challenge.getOpenid());

        } else {

        }
        challenge.setChallengeid(GetUUID.getUUID());
        /*red.setRedid(GetUUID.getUUID());
        red.setChallengeid(challenge.getChallengeid());
        red.setBalance(challenge.getTotalMoney());
        red.setPeopleNum(challenge.getPeopleNum());
        redService.insertRed(red);*/
        challengeService.insertChallenge(challenge);
        return null;
    }

    @RequestMapping("/selectchallengedetail")
    @ResponseBody
    public Map selectchallengedetail(@RequestBody Map m){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginTimeStr = null;
        Map map = new HashMap();
        String openid = m.get("openid").toString();
        String challengeid = m.get("challengeid").toString();
        Red red =  redService.selectRedByChallengeid(challengeid);
        Challenge challenge = challengeService.selectChallengeByOpenid(openid,challengeid);
        if(challenge.getChallengeTypeid().equals("1")){
            Double balance = red.getBalance();
            List<ChallengeStatus> list = challengeStatusService.selectChallengStatusByChallengeid(challengeid);
            map.put("challengeMessage", challenge);
            map.put("challengeDetail", list);
            map.put("msg","1");
            if(balance == 0) {
                map.put("msg","0");
            }
        }

        /*if(challenge.getChallengeTypeid().equals("2")) {
            List<ChallengeStatus> list = challengeStatusService.selectChallengStatusByChallengeid(challengeid);
            map.put("challengeMessage", challenge);
            map.put("challengeDetail", list);
            //竞赛模式结束时间
            long time = challenge.getEndTime().getTime();
            long time1 = beginTimeStr.getTime();
            if (time - time1 < 0) {
                map.put("msg", "竞赛限制时间已经过了");
            }
        }*/
        return map;
    }



    @RequestMapping("/savechallenge")
    @ResponseBody
    public Map savechallenge(@RequestBody ChallengeStatus challengeStatus, HttpServletRequest request){
        Map map = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginTimeStr = null;
        try {
            beginTimeStr = sdf.parse(challengeStatus.getBeginTimeStr());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Challenge challenge = challengeService.selectChallengeByChallengeid(challengeStatus.getChallengeid());
//        int i = challengeStatusService.selectNumByOpenid(challengeStatus.getOpenid());
//        if(i <= 0){
        Red red =  redService.selectRedByChallengeid(challengeStatus.getChallengeid());
        challengeStatus.setChallengeStatusid(GetUUID.getUUID());
        if(challengeStatus.getChallengeTypeid().equals("1")){
            if(red.getPeopleNum()!=0){
                if (challengeStatus.getIsPass().equals("1")) {
                    double getMoney = MathRandom.RedRandom(red.getBalance(), red.getPeopleNum());
                    RedStatus redStatus = new RedStatus();
                    redStatus.setRedStatusid(GetUUID.getUUID());
                    redStatus.setChallengeid(challengeStatus.getChallengeid());
                    redStatus.setRedid(red.getRedid());
                    redStatus.setMoney(getMoney);
                    redStatus.setOpenid(challengeStatus.getOpenid());
                    redStatus.setTime(new Date());
                    redStatusService.insertRedStatus(redStatus);
                    challengeStatus.setGetMoney(getMoney);

                    red.setBalance(red.getBalance()-getMoney);
                    red.setPeopleNum(red.getPeopleNum()-1);
                    redService.updateRed(red);
                    //通过普通模式并且有红包拿
                    map.put("challengeStatus",challengeStatus);
                }
                if(challengeStatus.getIsPass().equals("0")){
                    challengeStatus.setGetMoney(0);
                }
                challengeStatus.setBeginTime(beginTimeStr);
                challengeStatusService.addChallengeStatus(challengeStatus);
                //未通过普通模式
                map.put("challengeStatus",challengeStatus);
            }else{
                //红包已经发完
                map.put("msg","红包已经发完");
            }
        }
        if(challengeStatus.getChallengeTypeid().equals("2")){
            challengeStatus.setGetMoney(0);
            //竞赛模式结束时间
            long time = challenge.getEndTime().getTime();
            long time1 = beginTimeStr.getTime();
            if(time-time1>0){

                challengeStatus.setBeginTime(beginTimeStr);
                challengeStatusService.addChallengeStatus(challengeStatus);
                //通过竞赛模式
                map.put("challengeStatus",challengeStatus);
            }else {
                map.put("msg","竞赛限制时间已经过了");
            }
        }
//        }
//        else {
//            map.put("msg","该用户已经闯过关了");
//        }
        return map;

    }
}
